import { ref } from 'vue'
import { queuedFetch } from '../utils/queuedRequest.js'

/**
 * 机构号与名称的映射关系
 */
const ORG_NAME_MAP = {
  '00000': '东莞农村商业银行',
  '01000': '中堂支行',
  '02000': '望牛墩支行',
  '03000': '道滘支行',
  '04000': '洪梅支行',
  '05000': '麻涌支行',
  '06000': '万江支行',
  '07000': '虎门支行',
  '08000': '长安支行',
  '09000': '厚街支行',
  '10000': '沙田支行',
  '11000': '南城支行',
  '12000': '东城支行',
  '13000': '寮步支行',
  '14000': '大岭山支行',
  '15000': '大朗支行',
  '16000': '黄江支行',
  '17000': '樟木头支行',
  '18000': '清溪支行',
  '19000': '塘厦支行',
  '20000': '凤岗支行',
  '21000': '谢岗支行',
  '22000': '常平支行',
  '23000': '桥头支行',
  '24000': '横沥支行',
  '25000': '东坑支行',
  '26000': '企石支行',
  '27000': '石排支行',
  '28000': '茶山支行',
  '29000': '石碣支行',
  '30000': '高埗支行',
  '31000': '东联支行',
  '32000': '石龙支行',
  '33000': '松山湖科技支行',
  '37000': '总行(并表)',
  '38000': '中心支行',
  '39000': '私人银行部',
  '50000': '惠州支行',
  '51000': '清新支行',
  '52000': '南沙分行',
  '53000': '横琴分行',
  '55000': '滨海湾新区支行'
}

/**
 * 资产质量数据获取
 * 用于获取资产质量页面所需的各项指标数据
 */
export function useAssetQuality() {
  const isLoading = ref(false)
  const error = ref(null)
  const assetData = ref({})

  /**
   * 执行SQL查询的通用方法
   */
  const executeSQL = async (sql, description = '') => {
    return new Promise((resolve, reject) => {
      try {
        console.log(`[资产质量] 开始执行查询: ${description}`)
        console.log(`[资产质量] SQL: ${sql}`)
        
        // 准备POST数据
        const postData = new URLSearchParams()
        postData.append('action', 'exesql')
        postData.append('jdbcName', 'amsedb')  // 使用MySQL数据源（audit_index_total表在MySQL的fms库中）
        postData.append('enc', 'true')
        
        // SQL编码：先URL编码，再Base64编码
        const encodedSQL = btoa(encodeURIComponent(sql))
        postData.append('sql', encodedSQL)
        
        postData.append('pageIndex', 'undefined')
        postData.append('pageSize', '100')
        postData.append('isSys', 'false')
        postData.append('t', Date.now().toString())
        
        // API URL
        const apiUrl = `http://${window.location.host}/coolv/edatasource/jdbcmgr.do`
        
        // 使用队列化请求
        queuedFetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
          },
          body: postData.toString()
        }, {
          name: `资产质量-${description}`,
          priority: 8
        })
        .then(response => {
          if (!response.ok) {
            throw new Error(`请求失败: ${response.status}`)
          }
          return response.json()
        })
        .then(jsonResponse => {
          console.log(`[资产质量] ${description} 查询成功:`, jsonResponse)
          resolve(jsonResponse)
        })
        .catch(e => {
          console.error(`[资产质量] ${description} 查询失败:`, e)
          reject(e)
        })
        
      } catch (e) {
        console.error(`[资产质量] ${description} 异常:`, e)
        reject(e)
      }
    })
  }

  /**
   * 获取不良贷款率、不良贷款余额、不良贷款净生成率
   * 
   * 字段顺序说明：
   * row[0] = buss_dt      (业务日期)
   * row[1] = index_nm     (指标名称)
   * row[2] = org_no       (机构号)
   * row[3] = index_value  (指标值) ⭐ 主要使用
   * row[4] = ori          (来源)
   */
  const fetchBadLoanIndicators = async (orgNo = '00000') => {
    try {
      console.log(`[资产质量] 开始获取不良贷款相关指标，机构号: ${orgNo}`)
      
      // SQL查询：获取不良贷款率、不良贷款余额、月度贷款核销本金、月度核销后收回本金
      const sql = `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where org_no='${orgNo}' and index_nm in ('不良贷款余额','不良贷款率','月度贷款核销本金','月度核销后收回本金') and ori='审计还原-总行类指标' order by buss_dt`
      
      console.log(`[资产质量] 执行SQL: ${sql}`)
      
      const result = await executeSQL(sql, '不良贷款指标')
      
      if (!result || !result.datas || result.datas.length === 0) {
        console.warn('[资产质量] 未查询到不良贷款指标数据')
        return {
          badLoanRate: [],
          badLoanBalance: [],
          writeOffPrincipal: [],
          recoveredPrincipal: []
        }
      }

      // 按指标名称分组数据
      const grouped = {
        badLoanRate: [],        // 不良贷款率
        badLoanBalance: [],     // 不良贷款余额
        writeOffPrincipal: [],  // 月度贷款核销本金
        recoveredPrincipal: []  // 月度核销后收回本金
      }

      result.datas.forEach(row => {
        // 确保row是数组且有足够的元素
        if (!Array.isArray(row) || row.length < 4) {
          console.warn('[资产质量] 数据行格式不正确:', row)
          return
        }
        
        const bussDate = row[0]
        const indexName = row[1]
        const indexValue = parseFloat(row[3]) || 0
        
        const dataPoint = {
          date: bussDate,
          value: indexValue,
          name: indexName,
          orgNo: row[2],
          ori: row[4]
        }

        switch (indexName) {
          case '不良贷款率':
            grouped.badLoanRate.push(dataPoint)
            break
          case '不良贷款余额':
            grouped.badLoanBalance.push(dataPoint)
            break
          case '月度贷款核销本金':
            grouped.writeOffPrincipal.push(dataPoint)
            break
          case '月度核销后收回本金':
            grouped.recoveredPrincipal.push(dataPoint)
            break
          default:
            console.warn(`[资产质量] 未知指标名称: ${indexName}`)
        }
      })

      // 按日期排序
      Object.keys(grouped).forEach(key => {
        grouped[key].sort((a, b) => a.date.localeCompare(b.date))
      })

      console.log('[资产质量] 不良贷款指标数据处理完成:', grouped)
      
      return grouped
    } catch (err) {
      console.error('[资产质量] 获取不良贷款指标失败:', err)
      throw err
    }
  }

  /**
   * 计算不良贷款净生成率
   * 
   * 公式：不良贷款净生成率 = (期末不良贷款余额 - 期初不良贷款余额 + 核销 - 收回) / 各项贷款平均余额
   * 
   * @param {Array} badLoanBalanceData - 不良贷款余额数据
   * @param {Array} writeOffData - 核销数据
   * @param {Array} recoveredData - 收回数据
   * @param {Array} totalLoanData - 各项贷款余额数据（用于计算平均余额）
   * @returns {Array} 不良贷款净生成率数据
   */
  const calculateBadLoanNetGenerationRate = (badLoanBalanceData, writeOffData, recoveredData, totalLoanData) => {
    try {
      if (!badLoanBalanceData || badLoanBalanceData.length < 2) {
        console.warn('[资产质量] 不良贷款余额数据不足，无法计算净生成率')
        return []
      }

      const result = []
      
      // 从第二个月开始计算（需要期初数据）
      for (let i = 1; i < badLoanBalanceData.length; i++) {
        const currentMonth = badLoanBalanceData[i]
        const previousMonth = badLoanBalanceData[i - 1]
        
        // 期末不良贷款余额
        const endBalance = currentMonth.value
        // 期初不良贷款余额
        const startBalance = previousMonth.value
        
        // 查找当月的核销和收回数据
        const currentDate = currentMonth.date
        const writeOff = writeOffData.find(item => item.date === currentDate)?.value || 0
        const recovered = recoveredData.find(item => item.date === currentDate)?.value || 0
        
        // 计算各项贷款平均余额（期初+期末）/2
        const currentLoan = totalLoanData.find(item => item.date === currentDate)?.value || 0
        const previousLoan = totalLoanData.find(item => item.date === previousMonth.date)?.value || 0
        const avgLoan = (currentLoan + previousLoan) / 2
        
        if (avgLoan === 0) {
          console.warn(`[资产质量] ${currentDate} 各项贷款平均余额为0，跳过计算`)
          continue
        }
        
        // 计算净生成率
        const netGeneration = endBalance - startBalance + writeOff - recovered
        const netGenerationRate = (netGeneration / avgLoan) * 100
        
        result.push({
          date: currentDate,
          value: netGenerationRate,
          name: '不良贷款净生成率',
          // 保存计算详情，便于调试
          details: {
            endBalance,
            startBalance,
            writeOff,
            recovered,
            avgLoan,
            netGeneration
          }
        })
      }
      
      console.log('[资产质量] 不良贷款净生成率计算完成:', result)
      return result
    } catch (err) {
      console.error('[资产质量] 计算不良贷款净生成率失败:', err)
      return []
    }
  }

  /**
   * 获取各项贷款余额数据（用于计算净生成率）
   */
  const fetchTotalLoanBalance = async (orgNo = '00000') => {
    try {
      const sql = `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where org_no='${orgNo}' and index_nm='各项贷款总额' and ori='审计还原-总行类指标' order by buss_dt`
      
      console.log(`[资产质量] 获取各项贷款总额，SQL: ${sql}`)
      
      const result = await executeSQL(sql, '各项贷款余额')
      
      if (!result || !result.datas || result.datas.length === 0) {
        console.warn('[资产质量] 未查询到各项贷款余额数据')
        return []
      }

      const data = result.datas.map(row => ({
        date: row[0],
        value: parseFloat(row[3]) || 0,
        name: row[1]
      }))

      // 按日期排序
      data.sort((a, b) => a.date.localeCompare(b.date))
      
      console.log('[资产质量] 各项贷款余额数据获取完成:', data)
      return data
    } catch (err) {
      console.error('[资产质量] 获取各项贷款余额失败:', err)
      throw err
    }
  }

  /**
   * 获取逾期贷款数据（60天和90天）
   */
  const fetchOverdueLoanData = async (orgNo = '00000') => {
    try {
      console.log(`[资产质量] 开始获取逾期贷款数据，机构号: ${orgNo}`)
      
      // 并行查询逾期60天、逾期90天和不良贷款余额
      const [result60, result90, resultBad] = await Promise.all([
        executeSQL(
          `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where org_no='${orgNo}' and index_nm='逾期60天不良贷款余额' and ori='审计还原-总行类指标' order by buss_dt`,
          '逾期60天不良贷款余额'
        ),
        executeSQL(
          `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where org_no='${orgNo}' and index_nm='逾期90天不良贷款余额' and ori='审计还原-总行类指标' order by buss_dt`,
          '逾期90天不良贷款余额'
        ),
        executeSQL(
          `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where org_no='${orgNo}' and index_nm='不良贷款余额' and ori='审计还原-总行类指标' order by buss_dt`,
          '不良贷款余额（分母）'
        )
      ])

      // 解析数据
      const parseData = (result) => {
        if (!result || !result.datas || result.datas.length === 0) {
          return []
        }
        return result.datas.map(row => {
          if (!Array.isArray(row) || row.length < 4) {
            return null
          }
          return {
            date: row[0],
            value: parseFloat(row[3]) || 0
          }
        }).filter(item => item !== null)
      }

      const overdue60Data = parseData(result60)
      const overdue90Data = parseData(result90)
      const badLoanData = parseData(resultBad)

      // 计算占比
      const calculateRatio = (overdueData, badData) => {
        return overdueData.map(overdueItem => {
          const badItem = badData.find(b => b.date === overdueItem.date)
          if (!badItem || badItem.value === 0) {
            return {
              date: overdueItem.date,
              value: 0
            }
          }
          return {
            date: overdueItem.date,
            value: (overdueItem.value / badItem.value) * 100 // 转换为百分比
          }
        })
      }

      const overdue60Ratio = calculateRatio(overdue60Data, badLoanData)
      const overdue90Ratio = calculateRatio(overdue90Data, badLoanData)

      console.log('[资产质量] 逾期贷款数据获取成功')
      console.log('[资产质量] 逾期60天占比:', overdue60Ratio.length, '条')
      console.log('[资产质量] 逾期90天占比:', overdue90Ratio.length, '条')

      return {
        overdue60Ratio,
        overdue90Ratio
      }
    } catch (err) {
      console.error('[资产质量] 获取逾期贷款数据失败:', err)
      throw err
    }
  }

  /**
   * 获取拨备覆盖率数据
   */
  const fetchProvisionCoverageRatio = async (orgNo = '00000') => {
    try {
      console.log(`[资产质量] 开始获取拨备覆盖率数据，机构号: ${orgNo}`)
      
      const sql = `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where org_no='${orgNo}' and ori='信用风险指标补录表' and index_nm='拨备覆盖率' order by buss_dt`
      
      const result = await executeSQL(sql, '拨备覆盖率')
      
      if (!result || !result.datas || result.datas.length === 0) {
        console.warn('[资产质量] 未查询到拨备覆盖率数据')
        return []
      }

      const provisionCoverageRatioData = result.datas.map(row => {
        if (!Array.isArray(row) || row.length < 4) {
          console.warn('[资产质量] 拨备覆盖率数据行格式不正确:', row)
          return null
        }
        
        return {
          date: row[0],
          value: parseFloat(row[3]) || 0
        }
      }).filter(item => item !== null)

      console.log('[资产质量] 拨备覆盖率数据获取成功，共', provisionCoverageRatioData.length, '条')
      return provisionCoverageRatioData
    } catch (err) {
      console.error('[资产质量] 获取拨备覆盖率数据失败:', err)
      throw err
    }
  }

  /**
   * 获取完整的资产质量数据（包含拨备覆盖率）
   */
  const fetchAssetQualityData = async (orgNo = '00000') => {
    isLoading.value = true
    error.value = null

    try {
      console.log('[资产质量] 开始获取完整资产质量数据...')
      
      // 并行获取不良贷款指标、各项贷款余额、拨备覆盖率、逾期贷款数据、关注类贷款占比和迁徙率
      const [badLoanData, totalLoanData, provisionCoverageRatioData, overdueLoanData, attentionLoanRatioData, migrationRateData] = await Promise.all([
        fetchBadLoanIndicators(orgNo),
        fetchTotalLoanBalance(orgNo),
        fetchProvisionCoverageRatio(orgNo),
        fetchOverdueLoanData(orgNo),
        fetchAttentionLoanRatio(orgNo),
        fetchMigrationRate(orgNo)
      ])

      // 计算不良贷款净生成率
      const netGenerationRate = calculateBadLoanNetGenerationRate(
        badLoanData.badLoanBalance,
        badLoanData.writeOffPrincipal,
        badLoanData.recoveredPrincipal,
        totalLoanData
      )

      const data = {
        badLoanRate: badLoanData.badLoanRate,           // 不良贷款率
        badLoanBalance: badLoanData.badLoanBalance,     // 不良贷款余额
        provisionCoverageRatio: provisionCoverageRatioData, // 拨备覆盖率
        overdue60Ratio: overdueLoanData.overdue60Ratio, // 逾期60天占比
        overdue90Ratio: overdueLoanData.overdue90Ratio, // 逾期90天占比
        attentionLoanRatio: attentionLoanRatioData,     // 关注类贷款占比
        migrationRate: migrationRateData,               // 关注类贷款迁徙率
        netGenerationRate: netGenerationRate,           // 不良贷款净生成率（计算得出，用于其他用途）
        writeOffPrincipal: badLoanData.writeOffPrincipal,   // 核销本金
        recoveredPrincipal: badLoanData.recoveredPrincipal, // 收回本金
        totalLoanBalance: totalLoanData                 // 各项贷款余额
      }

      assetData.value = data
      
      console.log('[资产质量] 完整资产质量数据获取成功')
      return data
    } catch (err) {
      error.value = err
      console.error('[资产质量] 获取完整资产质量数据失败:', err)
      throw err
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取行业不良贷款数据（用于风险下钻地图）
   */
  const fetchIndustryBadLoanData = async (orgNo = '00000', bussDate = null) => {
    try {
      console.log(`[资产质量] 开始获取行业不良贷款数据，机构号: ${orgNo}`)
      
      // 构建SQL - 使用 IN 子句列出所有行业不良指标，避免 LIKE '%xxx%' 的编码问题
      const industryIndicators = [
        '行业不良-IT行业不良贷款余额',
        '行业不良-住宿和餐饮业不良贷款余额',
        '行业不良-公共事业不良贷款余额',
        '行业不良-公共管理、社会保障和社会组织不良贷款余额',
        '行业不良-其他贷款不良贷款余额',
        '行业不良-农林牧渔不良贷款余额',
        '行业不良-制造业不良贷款余额',
        '行业不良-卫生和社会工作不良贷款余额',
        '行业不良-居民服务、修理和其他服务业不良贷款余额',
        '行业不良-建筑业不良贷款余额',
        '行业不良-房地产行业不良贷款余额',
        '行业不良-批发和零售业不良贷款余额',
        '行业不良-教育不良贷款余额',
        '行业不良-文化、体育和娱乐业不良贷款余额',
        '行业不良-水利、环境和公共设施管理业不良贷款余额',
        '行业不良-消费贷款不良贷款余额',
        '行业不良-物流行业不良贷款余额',
        '行业不良-科学研究和技术服务业不良贷款余额',
        '行业不良-租赁和商务服务业不良贷款余额',
        '行业不良-采矿业不良贷款余额'
      ]
      
      const indicatorList = industryIndicators.map(name => `'${name}'`).join(',')
      let sql = `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where org_no='${orgNo}' and index_nm in (${indicatorList}) and ori='审计还原-总行类指标'`
      
      // 如果指定了日期，只查询该日期的数据
      if (bussDate) {
        sql += ` and buss_dt='${bussDate}'`
      }
      
      sql += ` order by buss_dt desc, index_nm`
      
      console.log(`[资产质量] 执行SQL（使用IN子句查询${industryIndicators.length}个行业指标）`)
      
      const result = await executeSQL(sql, '行业不良贷款数据')
      
      if (!result || !result.datas || result.datas.length === 0) {
        console.warn('[资产质量] 未查询到行业不良贷款数据')
        return []
      }

      // 按行业分组数据
      const industryMap = new Map()
      
      result.datas.forEach(row => {
        if (!Array.isArray(row) || row.length < 4) {
          console.warn('[资产质量] 数据行格式不正确:', row)
          return
        }
        
        const bussDate = row[0]
        const indexName = row[1]  // 例如：行业不良-制造业不良贷款余额
        const indexValue = parseFloat(row[3]) || 0
        
        // 提取行业名称（去掉"行业不良-"前缀和"不良贷款余额"后缀）
        const industryName = indexName
          .replace('行业不良-', '')
          .replace('不良贷款余额', '')
          .trim()
        
        if (!industryMap.has(industryName)) {
          industryMap.set(industryName, [])
        }
        
        industryMap.get(industryName).push({
          date: bussDate,
          industry: industryName,
          value: indexValue,
          originalName: indexName
        })
      })

      // 转换为数组格式
      const industryData = Array.from(industryMap.entries()).map(([industry, data]) => {
        // 如果有多个日期的数据，取最新的
        const latestData = data.sort((a, b) => b.date.localeCompare(a.date))[0]
        return {
          name: industry,
          value: latestData.value,
          date: latestData.date,
          // 计算不良率需要各项贷款余额，这里暂时不计算
          rate: 0
        }
      })

      // 按不良贷款余额降序排序
      industryData.sort((a, b) => b.value - a.value)

      console.log('[资产质量] 行业不良贷款数据处理完成:', industryData)
      
      return industryData
    } catch (err) {
      console.error('[资产质量] 获取行业不良贷款数据失败:', err)
      throw err
    }
  }

  /**
   * 获取关注类贷款占比数据（用于未来风险预警）
   */
  const fetchAttentionLoanRatio = async (orgNo = '00000') => {
    try {
      console.log(`[资产质量] 开始获取关注类贷款占比数据，机构号: ${orgNo}`)
      
      const sql = `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where org_no='${orgNo}' and index_nm='关注类贷款占比' and ori='审计还原-总行类指标' order by buss_dt`
      
      const result = await executeSQL(sql, '关注类贷款占比')
      
      if (!result || !result.datas || result.datas.length === 0) {
        console.warn('[资产质量] 未查询到关注类贷款占比数据')
        return []
      }

      const attentionLoanRatioData = result.datas.map(row => {
        if (!Array.isArray(row) || row.length < 4) {
          console.warn('[资产质量] 关注类贷款占比数据行格式不正确:', row)
          return null
        }
        
        return {
          date: row[0],
          value: parseFloat(row[3]) || 0
        }
      }).filter(item => item !== null)

      console.log('[资产质量] 关注类贷款占比数据获取成功，共', attentionLoanRatioData.length, '条')
      return attentionLoanRatioData
    } catch (err) {
      console.error('[资产质量] 获取关注类贷款占比数据失败:', err)
      throw err
    }
  }

  /**
   * 获取账龄分析数据（Vintage Analysis）
   */
  const fetchVintageAnalysisData = async (bussDate = null) => {
    try {
      console.log(`[资产质量] 开始获取账龄分析数据`)
      
      // 构建SQL，如果指定了日期则只查询该日期，否则查询所有历史数据
      let sql = `select buss_dt, index_nm, index_value from audit_index_total where ori='审计还原-总行类指标' and index_nm in ('一年内不良贷款余额','1-2年不良贷款余额','2-3年不良贷款余额','3年以上不良贷款余额')`
      
      if (bussDate) {
        sql += ` and buss_dt='${bussDate}'`
      }
      
      sql += ` order by buss_dt desc, index_nm`
      
      const result = await executeSQL(sql, '账龄分析数据')
      
      if (!result || !result.datas || result.datas.length === 0) {
        console.warn('[资产质量] 未查询到账龄分析数据')
        return []
      }

      // 按日期分组数据
      const dataByDate = {}
      
      result.datas.forEach(row => {
        if (!Array.isArray(row) || row.length < 3) {
          console.warn('[资产质量] 账龄分析数据行格式不正确:', row)
          return
        }
        
        const date = row[0]
        const indexName = row[1]
        const value = parseFloat(row[2]) || 0
        
        if (!dataByDate[date]) {
          dataByDate[date] = {
            date: date,
            '一年内': 0,
            '1-2年': 0,
            '2-3年': 0,
            '3年以上': 0
          }
        }
        
        // 映射指标名称到简短名称
        if (indexName === '一年内不良贷款余额') {
          dataByDate[date]['一年内'] += value
        } else if (indexName === '1-2年不良贷款余额') {
          dataByDate[date]['1-2年'] += value
        } else if (indexName === '2-3年不良贷款余额') {
          dataByDate[date]['2-3年'] += value
        } else if (indexName === '3年以上不良贷款余额') {
          dataByDate[date]['3年以上'] += value  // 聚合多条记录
        }
      })
      
      // 转换为数组并排序
      const vintageData = Object.values(dataByDate).sort((a, b) => {
        return String(a.date).localeCompare(String(b.date))
      })

      console.log('[资产质量] 账龄分析数据获取成功，共', vintageData.length, '个时间点')
      console.log('[资产质量] 最新账龄数据:', vintageData[vintageData.length - 1])
      
      return vintageData
    } catch (err) {
      console.error('[资产质量] 获取账龄分析数据失败:', err)
      throw err
    }
  }

  /**
   * 获取关注类贷款迁徙率数据（用于未来风险预警）
   */
  const fetchMigrationRate = async (orgNo = '00000') => {
    try {
      console.log(`[资产质量] 开始获取关注类贷款迁徙率数据，机构号: ${orgNo}`)
      
      const sql = `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where org_no='${orgNo}' and index_nm='关注类贷款迁徙率' and ori='指标结果表' order by buss_dt`
      
      const result = await executeSQL(sql, '关注类贷款迁徙率')
      
      if (!result || !result.datas || result.datas.length === 0) {
        console.warn('[资产质量] 未查询到关注类贷款迁徙率数据')
        return []
      }

      const migrationRateData = result.datas.map(row => {
        if (!Array.isArray(row) || row.length < 4) {
          console.warn('[资产质量] 关注类贷款迁徙率数据行格式不正确:', row)
          return null
        }
        
        return {
          date: row[0],
          value: parseFloat(row[3]) || 0  // 数据库中是小数，需要乘以100转为百分比
        }
      }).filter(item => item !== null)

      console.log('[资产质量] 关注类贷款迁徙率数据获取成功，共', migrationRateData.length, '条')
      return migrationRateData
    } catch (err) {
      console.error('[资产质量] 获取关注类贷款迁徙率数据失败:', err)
      throw err
    }
  }

  /**
   * 获取各支行不良贷款数据（用于风险下钻地图）
   */
  const fetchBranchBadLoanData = async (bussDate = null) => {
    try {
      console.log(`[资产质量] 开始获取各支行不良贷款数据`)
      
      // 构建SQL - 获取所有支行的不良贷款余额
      let sql = `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where index_nm='不良贷款余额' and ori='指标结果表'`
      
      // 如果指定了日期，只查询该日期的数据
      if (bussDate) {
        sql += ` and buss_dt='${bussDate}'`
      }
      
      sql += ` order by buss_dt desc, index_value desc`
      
      console.log(`[资产质量] 执行SQL: ${sql}`)
      
      const result = await executeSQL(sql, '各支行不良贷款数据')
      
      if (!result || !result.datas || result.datas.length === 0) {
        console.warn('[资产质量] 未查询到各支行不良贷款数据')
        return []
      }

      // 按日期分组，取最新日期的数据
      const dateMap = new Map()
      
      result.datas.forEach(row => {
        if (!Array.isArray(row) || row.length < 4) {
          console.warn('[资产质量] 数据行格式不正确:', row)
          return
        }
        
        const bussDate = row[0]
        const orgNo = row[2]
        const indexValue = parseFloat(row[3]) || 0
        
        // 排除总行数据（00000, 0A000等）和非支行机构（37000总行并表, 39000私人银行部）
        if (orgNo === '00000' || orgNo === '0A000' || orgNo.startsWith('0A') || orgNo === '37000' || orgNo === '39000') {
          return
        }
        
        if (!dateMap.has(bussDate)) {
          dateMap.set(bussDate, [])
        }
        
        dateMap.get(bussDate).push({
          date: bussDate,
          orgNo: orgNo,
          value: indexValue
        })
      })

      // 取最新日期的数据
      const dates = Array.from(dateMap.keys()).sort((a, b) => b.localeCompare(a))
      if (dates.length === 0) {
        console.warn('[资产质量] 没有可用的日期数据')
        return []
      }
      
      const latestDate = dates[0]
      const latestData = dateMap.get(latestDate)
      
      // 转换为数组格式，使用映射表获取支行名称
      const branchData = latestData.map(item => ({
        name: ORG_NAME_MAP[item.orgNo] || `${item.orgNo}支行`,
        value: item.value,
        date: item.date,
        orgNo: item.orgNo,
        rate: 0 // 暂时不计算不良率
      }))

      // 按不良贷款余额降序排序
      branchData.sort((a, b) => b.value - a.value)

      console.log('[资产质量] 各支行不良贷款数据处理完成，共', branchData.length, '个支行')
      console.log('[资产质量] 最新日期:', latestDate)
      
      return branchData
    } catch (err) {
      console.error('[资产质量] 获取各支行不良贷款数据失败:', err)
      throw err
    }
  }

  /**
   * 获取业务条线不良贷款数据（用于风险下钻地图）
   */
  const fetchBusinessLineBadLoanData = async (orgNo = '00000', bussDate = null) => {
    try {
      console.log(`[资产质量] 开始获取业务条线不良贷款数据，机构号: ${orgNo}`)
      
      // 业务条线列表
      const businessLines = [
        '零售条线不良贷款余额',
        '工商条线不良贷款余额',
        '普惠条线不良贷款余额',
        '转贴现条线不良贷款余额',
        '镇村条线不良贷款余额',
        '黄金借出条线不良贷款余额'
      ]
      
      // 并行查询所有业务条线数据
      const queries = businessLines.map(lineName => {
        let sql = `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where org_no='${orgNo}' and index_nm='${lineName}' and ori='审计还原-总行类指标'`
        if (bussDate) {
          sql += ` and buss_dt='${bussDate}'`
        }
        sql += ` order by buss_dt desc`
        return executeSQL(sql, lineName)
      })
      
      const results = await Promise.all(queries)
      
      // 解析数据
      const businessLineData = []
      
      results.forEach((result, index) => {
        if (!result || !result.datas || result.datas.length === 0) {
          console.warn(`[资产质量] 未查询到${businessLines[index]}数据`)
          return
        }
        
        // 取最新一条数据
        const latestRow = result.datas[0]
        if (!Array.isArray(latestRow) || latestRow.length < 4) {
          console.warn(`[资产质量] ${businessLines[index]}数据格式不正确:`, latestRow)
          return
        }
        
        const bussDate = latestRow[0]
        const indexValue = parseFloat(latestRow[3]) || 0
        
        // 提取条线名称（去掉"不良贷款余额"或"贷款余额"后缀）
        const lineName = businessLines[index]
          .replace('不良贷款余额', '')
          .replace('贷款余额', '')
          .trim()
        
        businessLineData.push({
          name: lineName,
          value: indexValue,
          date: bussDate,
          rate: 0 // 暂时不计算不良率
        })
      })
      
      // 按不良贷款余额降序排序
      businessLineData.sort((a, b) => b.value - a.value)
      
      console.log('[资产质量] 业务条线不良贷款数据处理完成:', businessLineData)
      
      return businessLineData
    } catch (err) {
      console.error('[资产质量] 获取业务条线不良贷款数据失败:', err)
      throw err
    }
  }

  /**
   * 获取最新值（用于显示当前指标）
   */
  const getLatestValue = (dataArray) => {
    if (!dataArray || dataArray.length === 0) return null
    return dataArray[dataArray.length - 1]
  }

  /**
   * 获取变化值（最新值 - 上一期值）
   */
  const getChange = (dataArray) => {
    if (!dataArray || dataArray.length < 2) return null
    const latest = dataArray[dataArray.length - 1]
    const previous = dataArray[dataArray.length - 2]
    return latest.value - previous.value
  }

  /**
   * 手动设置资产数据（用于从缓存恢复）
   * @param {Object} data - 资产数据对象
   */
  const setAssetData = (data) => {
    assetData.value = data
    console.log('[资产质量 Composable] 手动设置资产数据')
  }

  /**
   * 获取前十大不良贷款户数据
   * 数据源：audit_index_bad_loan_detail，来自 DB2 数据库 amsesdb
   */
  const fetchTopBadLoanCustomers = async (etlDate = '20250930') => {
    try {
      console.log(`[资产质量] 开始获取前十大不良贷款户数据，日期: ${etlDate}`)
      
      // SQL查询
      // 根据实际数据结构，使用select *然后根据位置索引解析
      const sql = `select * from audit_index_bad_loan_detail where index_name='总行前十大不良贷款户' and etl_dt='${etlDate}'`
      
      console.log(`[资产质量] 执行SQL: ${sql}`)
      
      // 准备POST数据，使用 DB2 数据源（amsedb）
      const postData = new URLSearchParams()
      postData.append('action', 'exesql')
      postData.append('jdbcName', 'amsedb')  // 使用 amsedb 数据源
      postData.append('enc', 'true')
      
      // SQL编码
      const encodedSQL = btoa(encodeURIComponent(sql))
      postData.append('sql', encodedSQL)
      
      postData.append('pageIndex', 'undefined')
      postData.append('pageSize', '500')
      postData.append('isSys', 'false')
      postData.append('t', Date.now().toString())
      
      const apiUrl = `http://${window.location.host}/coolv/edatasource/jdbcmgr.do`
      
      const response = await queuedFetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'X-Requested-With': 'XMLHttpRequest',
          'Accept': '*/*',
          'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
        },
        body: postData.toString()
      }, {
        name: `资产质量-前十大不良贷款户`,
        priority: 8
      })
      
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`)
      }
      
      const jsonResponse = await response.json()
      console.log(`[资产质量] 前十大不良贷款户查询成功:`, jsonResponse)
      
      if (!jsonResponse || !jsonResponse.datas || jsonResponse.datas.length === 0) {
        console.warn('[资产质量] 未查询到前十大不良贷款户数据')
        return []
      }
      
      // 解析数据并按客户分组
      const customerMap = new Map()
      
      jsonResponse.datas.forEach(row => {
        if (!Array.isArray(row) || row.length < 15) {
          console.warn('[资产质量] 数据行格式不正确:', row)
          return
        }
        
        // 根据实际表结构提取字段
        // row[6] = 客户名称
        // row[7] = 借据号
        // row[8] = 合同编号
        // row[9] = 卡号（信用卡）
        // row[10] = 放款日期
        // row[11] = 到期日期
        // row[12] = 币种
        // row[13] = 贷款金额
        // row[14] = 贷款余额（万元）
        // row[15] = 贷款余额（元）
        // row[16] = 产品类型编码
        // row[17] = 产品类型名称
        // row[21] = 五级分类
        const customerName = row[6] || '未知客户'
        const loanId = row[7] || row[9] || ''
        const contractNo = row[8] || ''
        const cardNo = row[9] || ''
        const loanDate = row[10] || ''
        const dueDate = row[11] || ''
        const currency = row[12] || 'CNY'
        const loanAmount = parseFloat(row[13]) || 0
        const balanceWan = parseFloat(row[14]) || 0
        const balance = parseFloat(row[15]) || 0
        const productCode = row[16] || ''
        const productName = row[17] || ''
        const riskLevel = row[21] || ''
        
        const loanDetails = {
          loanId: loanId,
          contractNo: contractNo,
          cardNo: cardNo,
          loanDate: loanDate,
          dueDate: dueDate,
          currency: currency,
          loanAmount: loanAmount,
          balanceWan: balanceWan,
          balance: balance,
          productCode: productCode,
          productName: productName,
          riskLevel: riskLevel,
          rawData: row
        }
        
        if (!customerMap.has(customerName)) {
          customerMap.set(customerName, {
            name: customerName,
            totalBalance: 0,
            loans: []
          })
        }
        
        const customer = customerMap.get(customerName)
        customer.totalBalance += balance
        customer.loans.push(loanDetails)
      })
      
      // 转换为数组并排序
      const customersData = Array.from(customerMap.values()).map(customer => ({
        name: customer.name,
        value: customer.totalBalance,
        loans: customer.loans,
        loanCount: customer.loans.length
      }))
      
      customersData.sort((a, b) => b.value - a.value)
      
      console.log('[资产质量] 前十大不良贷款户数据处理完成，共', customersData.length, '户')
      console.log('[资产质量] 前3户预览:', customersData.slice(0, 3))
      
      return customersData
    } catch (err) {
      console.error('[资产质量] 获取前十大不良贷款户数据失败:', err)
      throw err
    }
  }

  /**
   * 获取支行不良贷款率月度数据（用于动态排序图）
   */
  const fetchBranchNPLRateTimeSeries = async () => {
    try {
      console.log('[资产质量] 开始获取支行不良贷款率时序数据')
      
      const sql = `select buss_dt, index_nm, org_no, index_value, ori from audit_index_total where index_nm='不良贷款率' and org_no not in ('00000','81000') and ori='审计还原'`
      
      const postData = new URLSearchParams()
      postData.append('action', 'exesql')
      postData.append('jdbcName', 'amsedb')
      postData.append('enc', 'true')
      
      const encodedSQL = btoa(encodeURIComponent(sql))
      postData.append('sql', encodedSQL)
      
      postData.append('pageIndex', 'undefined')
      postData.append('pageSize', '2000')
      postData.append('isSys', 'false')
      postData.append('t', Date.now().toString())
      
      const apiUrl = `http://${window.location.host}/coolv/edatasource/jdbcmgr.do`
      
      const response = await queuedFetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'X-Requested-With': 'XMLHttpRequest',
          'Accept': '*/*',
          'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
        },
        body: postData.toString()
      }, {
        name: `资产质量-支行不良贷款率时序`,
        priority: 7
      })
      
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`)
      }
      
      const jsonResponse = await response.json()
      console.log(`[资产质量] 支行不良贷款率查询成功，共 ${jsonResponse.datas?.length || 0} 条`)
      console.log(`[资产质量] 前3条数据示例:`, jsonResponse.datas?.slice(0, 3))
      
      if (!jsonResponse || !jsonResponse.datas || jsonResponse.datas.length === 0) {
        console.warn('[资产质量] 未查询到支行不良贷款率数据')
        return []
      }
      
      // 返回原始数据，在组件中处理
      return jsonResponse.datas
    } catch (err) {
      console.error('[资产质量] 获取支行不良贷款率时序数据失败:', err)
      throw err
    }
  }

  return {
    isLoading,
    error,
    assetData,
    fetchAssetQualityData,
    fetchBadLoanIndicators,
    fetchTotalLoanBalance,
    calculateBadLoanNetGenerationRate,
    fetchAttentionLoanRatio,
    fetchMigrationRate,
    fetchVintageAnalysisData,
    fetchBranchBadLoanData,
    fetchIndustryBadLoanData,
    fetchBusinessLineBadLoanData,
    fetchTopBadLoanCustomers,  // 新增：获取前十大不良贷款户
    fetchBranchNPLRateTimeSeries,  // 新增：获取支行不良贷款率时序数据
    getLatestValue,
    getChange,
    executeSQL,
    setAssetData  // 新增：用于从缓存恢复数据
  }
}

